package wwl.lsf.hellospringboot.controller;

import java.io.IOException;
import java.io.InputStream;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringEscapeUtils;
import org.owasp.validator.html.AntiSamy;
import org.owasp.validator.html.CleanResults;
import org.owasp.validator.html.Policy;
import org.owasp.validator.html.PolicyException;
import org.owasp.validator.html.ScanException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Title
 * @Author wangwenliang
 * @Date 2020/8/3
 * @Description
 */
@Slf4j
@RestController
public class AntisamyController {

  @RequestMapping("/anti")
  public String test() {
    xssClean("wwl");
    return "测试完啦";
  }
  private String xssClean(String value) {
    AntiSamy antiSamy = new AntiSamy();
    try {
      ClassPathResource classPathResource = new ClassPathResource("config/antisamy.xml");
      InputStream inputStream = classPathResource.getInputStream();
      Policy policy = Policy.getInstance(inputStream);
      final CleanResults cr = antiSamy.scan(value, policy);
      //安全的HTML输出
      String safeHtml = cr.getCleanHTML();
      safeHtml = StringEscapeUtils.unescapeHtml(safeHtml);
      safeHtml = safeHtml.replaceAll(antiSamy.scan("&nbsp;", policy).getCleanHTML(), "");
      log.info(safeHtml);
      return safeHtml;
    } catch (ScanException e) {
      log.error("xssClean", e);
    } catch (PolicyException e) {
      log.error("xssClean", e);
    } catch (IOException e){
      log.error("xssClean", e);
    }
    return value;
  }
}
